package com.sdruixinggroup.mondayb2b.ui;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.ui.Activities.LoginActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.BuildConfig;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.math.BigDecimal;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by tangjie on 2017/11/11.
 */

public class SettingActivity extends BaseActivity {
    @BindView(R.id.bt_quit_out)
    Button btQuitOut;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.tv_cache_size)
    TextView tvCacheSize;
    @BindView(R.id.rl_clear_cache)
    RelativeLayout rlClearCache;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.topbar_title)
    TextView topbarTitle;
    @BindView(R.id.about_us)
    RelativeLayout aboutUs;
    private RelativeLayout about_us, change_psd;
    private ImageView topbar_left;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settting);
        ButterKnife.bind(this);

        initView();
    }

    private void initView() {
        topbarTitle.setText("设置");
        change_psd = (RelativeLayout) findViewById(R.id.change_psd);
        change_psd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(SettingActivity.this, CommitPassWord.class));
            }
        });


        about_us = (RelativeLayout) findViewById(R.id.about_us);
        about_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toWebView("about?");
            }
        });

        topbar_left = (ImageView) findViewById(R.id.topbar_left);
        topbar_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        try {
            double fileSize = getFolderSize(getCacheDir()) + getFolderSize(getFilesDir());
            if (isMethodsCompat(Build.VERSION_CODES.FROYO)) {
                fileSize += getFolderSize(getExternalCacheDir(getApplicationContext()));
            }
            tvCacheSize.setText(getFormatSize(fileSize));
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvVersion.setText("V" + BuildConfig.VERSION_NAME);
    }

    @OnClick(R.id.bt_quit_out)
    public void onClick() {
        progress.setVisibility(View.VISIBLE);
        String url = API.LOGOUT_TOKEN + UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };
        OkHttpUtils.post().url(url).headers(header).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                progress.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(ModelBeen response, int id) {

                if (null != response) {
                    showToast("退出成功");
                    UserInfoUtil.saveToken(getApplicationContext(), "");
                    EventBus.getDefault().post(124);
                    Intent inmain = new Intent();
                    inmain.setClass(SettingActivity.this, LoginActivity.class);
                   // inmain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    //inmain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(inmain);
                    finish();

                }
                progress.setVisibility(View.GONE);
            }
        });

    }

    /**
     * 清除app缓存
     *
     * @param mContext
     */
    public void clearAppCache(final Context mContext) {
//        清除的目录包括：
//        1./data/data/package_name/files
//        2./data/data/package_name/cache
//        3.<sdcard>/Android/data/<package_name>/cache/
//        4.webview缓存数据
        final Handler handlers = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
//                    showToast("缓存清除成功");
                } else {
                    showToast("缓存清除失败");
                }
            }
        };
        new Thread() {
            public void run() {
                Message msg = Message.obtain();
                try {
                    clearAppCache();
                    msg.what = 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = -1;
                }
                handlers.sendMessage(msg);
            }
        }.start();
    }


    /**
     * 清除app缓存
     */
    public void clearAppCache() {
        //WebView 缓存文件
        File appCacheDir = new File(getFilesDir().getAbsolutePath() + "/webcache");

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath() + "/webviewCache");
        //清理Webview缓存数据库
        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webview.db-shm");
            deleteDatabase("webview.db-wal");
            deleteDatabase("webviewCache.db");
            deleteDatabase("webviewCache.db-shm");
            deleteDatabase("webviewCache.db-wal");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //清除数据缓存
        deleteFile(getFilesDir());
        deleteFile(getCacheDir());
        //2.2版本才有将应用缓存转移到sd卡的功能
        if (isMethodsCompat(Build.VERSION_CODES.FROYO)) {
            deleteFile(getExternalCacheDir(getApplicationContext()));
        }
        System.gc();
    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {


        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        }
    }

    public boolean isMethodsCompat(int VersionCode) {
        int currentVersion = Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    @TargetApi(8)
    public File getExternalCacheDir(Context context) {

        // return context.getExternalCacheDir(); API level 8

        return context.getExternalCacheDir();
    }

    @OnClick(R.id.rl_clear_cache)
    public void onClickC() {
        clearAppCache(getApplicationContext());
        tvCacheSize.setText("0KB");
    }

    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size += getFolderSize(fileList[i]);
                } else {
                    size += fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }


    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    private void toWebView(String param) {
        Intent intent = new Intent(getBaseContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);
        startActivity(intent);
    }
}
